package com.jobboard.wx.handler;

import com.jobboard.wx.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class ReceiveTextMsgHandler implements WxChatMsgHandler {
    private static final String KEY_WORD = "验证码";

    private static final String LOGIN_PREFIX = "loginCode";
    @Resource
    private RedisUtil redisUtil;

    @Override
    public WxChatMsgTypeEnum getMsgType() {
        return WxChatMsgTypeEnum.TEXT_MSG;
    }

    @Override
    public String dealMsg(Map<String, String> messageMap) {
        log.info("接收到文本消息事件");
        String content = messageMap.get("Content");
        String fromUserName = messageMap.get("FromUserName");
        String toUserName = messageMap.get("ToUserName");
        if (!KEY_WORD.equals(content)) {
            return pleaseSendKeyWord(fromUserName,toUserName);
        }

        String num = generateVerificationCode(3);
        String numKey = redisUtil.buildKey(LOGIN_PREFIX, num);
        redisUtil.setNx(numKey, fromUserName, 5L, TimeUnit.MINUTES);
        String numContent = "您当前的验证码是：" + num + "，仅5分钟内有效";
        String replyContent = "<xml>\n" +
                "  <ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>\n" +
                "  <FromUserName><![CDATA[" + toUserName + "]]></FromUserName>\n" +
                "  <CreateTime>12345678</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA[" + numContent + "]]></Content>\n" +
                "</xml>";
        return replyContent;
    }

    private static String pleaseSendKeyWord(String fromUserName, String toUserName) {
        String subscribeContext = "请发送\'验证码\'";
        String replyContent = "<xml>\n" +
                "  <ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>\n" +
                "  <FromUserName><![CDATA[" + toUserName + "]]></FromUserName>\n" +
                "  <CreateTime>12345678</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA[" + subscribeContext + "]]></Content>\n" +
                "</xml>";
        return replyContent;
    }

    // 生成指定长度的验证码的方法
    private static String generateVerificationCode(int codeLength) {

        // 定义验证码字符集
        String codeChars = "0123456789aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ";
        StringBuilder verificationCode = new StringBuilder();   // 使用StringBuilder来拼接验证码

        // 创建Random对象
        Random random = new Random();
        for (int i = 0; i < codeLength; i++) {  // 循环生成指定长度的验证码
            char randomChar = codeChars.charAt(random.nextInt(codeChars.length()));   // 从字符集中随机选择一个字符
            verificationCode.append(randomChar); // 将选定的字符追加到验证码中
        }

        return verificationCode.toString();  // 返回生成的验证码字符串
    }
}
